<template>
  <div class='m-courseDetail'>
    <el-form :inline="false" class="form" ref='form' label-width="120px" :model="form" :rules='rules'>
      <el-form-item label="商品名称：" prop='name'>
        <el-input type="text" placeholder="请输入商品名称" v-model="form.name"></el-input>
      </el-form-item>
      <el-form-item label="商品说明：" prop='number'>
        <el-input type="text" placeholder="请输入商品说明" v-model="form.explain"></el-input>
      </el-form-item>


      <el-form-item v-for='(opt, index) in allClass.list' :key="index" :label="`${opt.name}:`">
        <selectAttrList
          ref="typeAttrList"
          openType='edit'
          :selectStatus="opt.id"
          :list="allClass.list"
          :skuList='skuList'
          :attrs="data.attrs"
          :def="2"
          :isSkuIndex="index"
          @getSku="selectListUpdate"></selectAttrList>
        <el-checkbox v-model="typeAttr.checked[index]" @change="skuListCreate">设为sku</el-checkbox>
      </el-form-item>

      <el-form-item label="商品属性：">
        <attr-list ref='attrList' aType='0' @getSku='attrListUpdateSku'/>
        <!--<el-checkbox v-model="typeAttr.checked[index+1]" @change="skuListCreate">设为sku</el-checkbox>-->
      </el-form-item>
      <el-form-item v-for="self in selfList" :label="self.name" :key="self.id">
        <el-select @remove-tag="createSelfSkus" v-model="self.selects" multiple>
        </el-select>
        <el-checkbox v-model="self.is_sku" @change="createSelfSkus">设为sku</el-checkbox>
      </el-form-item>

      <el-form-item label="商品sku">
        <!--表格-->
        <a-table :cols="cols" :data="data.skus">

          <el-table-column align="center" label="销售价" width='300'>
            <template slot-scope="scope">
              <div>
                <el-input v-model="data.skus[scope.$index].price"></el-input>
              </div>
            </template>
          </el-table-column>

          <el-table-column align="center" label="操作" width='150'>
            <template slot-scope="scope">
              <div>
                <el-button size='mini' @click='deleteObj(scope.$index,data.skus)'>删除</el-button>
              </div>
            </template>
          </el-table-column>
        </a-table>

      </el-form-item>

      <el-form-item align='left'>
        <el-button type="primary" @click="confirm">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
  import AttrList from '@/components/business/List'
  import {mapMutations} from 'vuex'
  import attrMixin from '@/mixins/attrs'
  import selectAttrList from './selectAttrList/selectAttrList3'
  import {formatDetailDataToAttrList} from '@/util/formatAttr'

  export default {
    name: 'su_goods_detail',
    components: {
      AttrList,
      selectAttrList
    },

    mixins: [attrMixin],
    data() {
      return {
        form: {
          name: '',
          explain: '',
          attr: ''
        },
        rules: {
          name: [
            {required: true, message: '请输入商品名称', trigger: 'blur'},
            {max: 20, min: 2, message: '长度为 2 - 20 个字符', trigger: 'blur'}
          ]
        },
        ifRequesting: false,
        type: 'add',
        id: '',
        typeAttrList: {},
        skuList: [],
        cols: [
          {label: '属性值', prop: 'name'}
        ],
        data: {
          skus: [
            {
              id: '',
              name: '',
              retail_price: 0,
              price: 0,
              goods_no: '',
              quantity: -0.01,
              pics: [ ]
            }
          ]
        },
        initSkus: [
          {
            id: '',
            name: '',
            retail_price: 0,
            price: 0,
            goods_no: '',
            quantity: -0.01,
            pics: [ ]
          }
        ],
        skus: [], //  用来保存初始化请求回来的skus
        typeAttr: {
          attrs: [],
          checked: []
        },
        createSkuChecked: '',
        saveList: [],
        jianList: [],
        allClass: [],
        selfSkus: [],
        selftIds: [],
        selfSkuSelect: false,
        selfList: [], // 自定义属性
        selfSkusSave: [],
        allList: [],
        selfJianList: []

      }
    },

    async created() {
      const {id} = this.$route.query
//      if (!id) return false
      this.id = id
      if (id) this.getMine()
      this.getAllAttrAndClass()
    },
    methods: {
      ...mapMutations(['setTabRoutes']),

      routerPush(type, args) {
        // push 到缓存里
        this.setTabRoutes({type: 'add', obj: {...this.getRouterInfoAccordingName(type), ...args}})
      },

      async getMine() {
        const {code, data} = await this.$api.supplyGetMine({
          aId: this.id
        })
        if (code === 0) {
          this.attrList = formatDetailDataToAttrList(data.attrs)
          this.data = data
          this.skus = this.data.skus
          this.form.name = data.name
          this.form.explain = data.desc
          this.createSelfList()
        }
      },

      createSelfList() {
        this.selfList = this.attrList.filter((item) => {
          return item.is_self_def === 1 || typeof (item.is_self_def) === 'undefined'
        })
        this.createSelfSkus()
      },
      createSelfSkus() {
        let _thisJIanList = []
        this.selfList.filter((v) => {
          if (v.is_sku === true) {
            _thisJIanList.push(this.selectListDataHandle(v))
            return true
          }
        })
        this.selfJianList = _thisJIanList

//        this.selfSkusSave.push(this.selfList[this.selfList.length - 1])
//        this.selfJianList.push(this.selectListDataHandle(this.selfList[this.selfList.length - 1]))
        this.skuListCreate()
      },

      async create() {
        this.attrList = this.attrList.concat(this.typeAttr.attrs)
        // 去除相同选择项
        this.attrList = this.quchong(this.attrList)

        let skus = []
        // 把sku转换成参数
        this.data.skus.forEach((item) => {
          skus.push({
            aName: item.name,
            aId: item.id,
            aPrice: item.price
          })
        })

        const {name, explain} = this.form
        let api = this.id ? 'supplyUpdate' : 'supplyCreate'
        let aMerchantId = this.id ? '' : this.aFirmId
        const params = {
          aMerchantId,
          aId: this.id,
          aName: name,
          aSkus: skus.length > 0 ? skus : [''],
          aDesc: explain,
          aAttrs: this.formatOutputData().length > 0 ? this.formatOutputData() : ['']
        }
        const {code} = await this.$api[api](params)
        if (code === 0) {
          this.__notify('修改成功')
          this.$router.push({name: 'sys_goods_manage'})
        }
      },

      // 去除重复输入的属性
      quchong(arr) {
        for (let i = 0; i < arr.length; i++) {
          for (let j = i + 1; j < arr.length; j++) {
            if (arr[i] && arr[i].hasOwnProperty('id')) {
              if (arr[i].id === arr[j].id) {
                arr[i].selects = Array.from(new Set(arr[i].selects.concat(arr[j].selects)))
                arr.splice(j, 1)
                i = i - 1
              }
            }
          }
        }
        return arr
      },

      confirm() {
        this.create()
      },

      reset() {
        this.$refs.form.resetFields()
      },

      closeAutoAttr(index, id) {
        this.attrList.splice(index, 1)
      },

      selectListUpdate(o, index, self) {
        let has = false
        // 把选择的属性保存起来
        if (this.saveList.length > 0) {
          this.saveList = this.saveList.map(v => {
            if (o.id === v.id) {
              has = true
              return o
            }
            return v
          })
          if (!has) {
            this.saveList.push(o)
          }
        } else {
          this.saveList.push(o)
        }
//        this.allList = this.quchongAllList(this.saveList.concat(this.selfSkusSave))
        // 处理数据
        if (this.saveList.length > 0) {
          for (let i = 0; i < this.saveList.length; i++) {
            this.jianList[i] = this.selectListDataHandle(this.saveList[i])
          }
        }
        this.typeAttr.attrs = this.saveList
//        if (self) this.skuListCreate()
        if (!this.typeAttr.checked[index]) return false
        this.skuListCreate()
      },

      // sku列表创建
      skuListCreate() {
        let list = []
        let names = []
        let ids = []
        let jianListArr = this.jianList.concat(this.selfJianList)
        jianListArr.forEach((v) => {
          names.push(v.names)
          ids.push(v.idS)
        })
        // 遍历checked 看看哪个 设为sku按钮 不勾选的把names的子类设置为空
        for (let i = 0; i < this.typeAttr.checked.length; i++) {
          if (!this.typeAttr.checked[i]) {
            names[i] = []
            ids[i] = []
          }
        }
//        if (names[0].length === 0) return false
        // 卡迪尔乘积处理
        let nameRes = this.cartesianProductOf(...names)
        let idRes = this.cartesianProductOf(...ids)

        if (nameRes.length === 0) return false

        //  构建skus属性
        for (let i = 0; i < nameRes.length; i++) {
          const name = nameRes[i] ? nameRes[i].toString().replace(/,/g, ';') : ''
          const id = idRes[i] ? idRes[i].toString().replace(/,/g, ';') : ''
          let key = {
            name: name,
            id: id,
            price: 0
          }
          list.push(key)
        }

        this.data.skus = this.skus.concat(list).filter(v => {
          if (v.name && v.id) return v
        })
      },

      // 卡迪尔乘积处理
      cartesianProductOf() {
        let params = []
        for (let i = 0; i < arguments.length; i++) {
          if (arguments[i].length > 0) params.push(arguments[i])
        }
        return Array.prototype.reduce.call(params, function(a, b) {
          let ret = []
          a.forEach(function(a) {
            b.forEach(function(b) {
              if (b) {
                ret.push(a.concat([b]))
              }
            })
          })
//          console.log(ret)
          return ret
        }, [[]])
      },

      // 处理返回数据
      selectListDataHandle(o) {
        let arrayName = []
        let arrayId = []
        // 遍历数据 获取选中的名字
        o.classes.map((item) => {
          if (item.child) {
            // 遍历二级
            item.child.map((item2) => {
              item.selects.map((item3) => {
                if (item2.id === item3) {
                  arrayName.push(item2.name)
                  arrayId.push(item2.id)
                }
              })
            })
          }

          // 遍历一级
          o.selects.map((item4) => {
            if (item.id === item4) {
              arrayName.push(item.name)
              arrayId.push(item.id)
            }
          })
        })
        return {
          names: arrayName,
          idS: arrayId
        }
      },
      deleteObj(index, rows) {
        if (rows.length - 1 === 0) {
          this.data.skus = this.initSkus
          return false
        }
        rows.splice(index, 1)
      },

      async getAllAttrAndClass() {
        const {code, data} = await this.$api.utilsGetAllClasses({
          aMerchantId: this.aFirmId, aType: 0
        })
        if (code === 0) {
          this.allClass = data
          // 加1 是因为自定义属性
          this.typeAttr.checked = new Array(data.list.length).fill(false) // 创建数组，冰赋值
        }
      },
      attrListUpdateSku(skuData) {
        // 将 sku 添加到 attrList 列表里
        const cacheArr = []
        // 把 attrList 和 skuData 相同 id 的属性和 attrList 必须的抽出来
        this.attrList = this.attrList.filter(v => {
          if (v.is_require === '1') return true
          return skuData.some((item) => {
            if (v.id === item.value) {
              cacheArr.push(item.value)
              return true
            }
            return true
          })
        })
        // 将有 skuId 的去除，再添加
        skuData.forEach((v, index) => {
          if (cacheArr.includes(v.value)) return false
          const {value} = v
          let selects = []
          v.classes.forEach((o) => {
            selects.push(o.id)
            v.selects = selects
          })

          // 只添加最后一项
          if (skuData.length - 1 === index) {
            this.attrList.push({
              ...v,
              skuId: value
            })
          }
        })
        this.createSelfList()
      }
    }
  }
</script>

<style lang='less'>
  .m-courseDetail {
    .addValue-list {
      display: flex;
      align-items: center;
      padding-bottom: 20px;
      .icon {
        margin-left: 20px;
      }
      &-child {
        padding-bottom: 10px;
      }
    }
    .form-data {
      width: 100%;
    }
    &_autoAttr {
      display: flex;
      align-items: center;
      .el-cascader, .el-input {
        flex: 1;
        margin-right: 15px;
      }
    }
    .createTheFormItem {
      .el-checkbox-group {
        display: flex;
        align-items: center;
        flex-wrap: wrap;
        width: 100%;
      }
      .el-checkbox {
        // flex: 1;
        width: 50%;
        display: flex;
        align-items: center;
        padding-right: 10px;
        box-sizing: border-box;
        &:nth-child(n+3) {
          padding-top: 10px;
        }
      }
      .el-checkbox + .el-checkbox {
        margin-left: 0;
      }
    }
  }
</style>
